package com.zh.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.zh.exception.GlobalException;
import com.zh.pojo.dto.UploadDto;
import com.zh.service.IUploadService;
import com.zh.template.CosTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;


@Slf4j
@Service
public class UploadServiceImpl implements IUploadService {

    @Autowired
    private CosTemplate cosTemplate;

    /**
     * 腾讯云对象存储COS_ 文件上传
     *
     * @param file      上传的文件文件
     * @param uploadDto 文件夹
     * @return
     */
    @Override
    public String cosUpload(MultipartFile file, UploadDto uploadDto) {
        // 获取 文件名后缀
        String filename = file.getOriginalFilename();
        String extName = FileUtil.extName(filename);
        try {
            InputStream fileInputStream = file.getInputStream();
            String imageUrl =cosTemplate.cosUploadForStream(fileInputStream, extName, uploadDto.getFolder());
            return imageUrl;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("文件上传失败");
        }

    }



}
